package com.atelier.plugin.database.action;

import com.atelier.plugin.database.domain.TreeExpansionState;
import com.atelier.plugin.database.ui.DataBaseToolWindowContent;
import com.atelier.plugin.database.util.ConnectionInfoTreeUtil;
import com.atelier.plugin.database.util.Constants;
import com.atelier.plugin.tool.ProjectUtils;
import com.intellij.icons.AllIcons;
import com.intellij.openapi.actionSystem.AnActionEvent;
import com.intellij.openapi.progress.ProgressIndicator;
import com.intellij.openapi.progress.ProgressManager;
import com.intellij.openapi.progress.Task;
import com.intellij.openapi.project.DumbAwareAction;
import com.intellij.openapi.project.Project;
import com.intellij.util.ui.tree.TreeUtil;
import org.jetbrains.annotations.NotNull;

import javax.swing.*;
import javax.swing.tree.TreePath;
import java.sql.SQLException;
import java.util.List;

public class RefreshAction extends DumbAwareAction {
    private final TreeExpansionState expansionState = new TreeExpansionState();

    public RefreshAction() {
        super("Refresh", "Refresh", AllIcons.Actions.Refresh);
    }

    /**
     * @param e Carries information on the invocation place
     */

    @Override
    public void actionPerformed(@NotNull AnActionEvent e) {
        Project project = ProjectUtils.getCurrProject();
        ProgressManager.getInstance().run(new Task.Backgroundable(project, "Loading database drivers") {
            @Override
            public void run(@NotNull ProgressIndicator indicator) {
                // 在这里执行耗时操作，例如刷新数据库树
                try {
                        JTree databaseTree = DataBaseToolWindowContent.getInstants().getDatabaseTree();
                    TreePath selectionPath = databaseTree.getSelectionPath();
                    // 保存当前的展开状态
                    List<TreePath> treePaths = expansionState.saveExpandedState(databaseTree);

                    // 在这里执行刷新数据库树的操作
                       ConnectionInfoTreeUtil.refreshTree(databaseTree);
                    databaseTree.expandPath(selectionPath);
                        // 还原展开状态
                   // expansionState.restoreExpandedState(databaseTree,treePaths);
                } catch (SQLException ex) {
                    throw new RuntimeException(ex);
                }
            }
        });
    }
}
